package com.example.librarymanagement.security;

import cn.hutool.core.util.StrUtil;
import com.example.librarymanagement.entity.User;
import com.example.librarymanagement.exception.CaptchaException;
import com.example.librarymanagement.result.ResultCode;
import com.example.librarymanagement.service.IUserService;
import com.example.librarymanagement.util.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @author fgba
 */
@Slf4j
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Resource
    private JwtUtils jwtUtils;

    @Resource
    private IUserService userService;

    @Resource
    private UserDetailsServiceImpl userDetailsService;

    @Resource
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String jwt = request.getHeader(jwtUtils.getHeader());
        if (StrUtil.isBlankOrUndefined(jwt)) {
            chain.doFilter(request, response);
            return;
        }

        Claims claim = jwtUtils.getClaimByToken(jwt);
        try {
            if (claim == null) {
                throw new CaptchaException(ResultCode.TOKEN_ERROR);
            }

            if (jwtUtils.isTokenExpired(claim)) {
                throw new CaptchaException(ResultCode.TOKEN_INVALID_OR_EXPIRED);
            }

            String username = claim.getSubject();
            User user = userService.getUserByUsername(username);
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, null, userDetailsService.getAuthorities(user.getId()));
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            login(username);
            chain.doFilter(request, response);
        } catch (CaptchaException e) {
            jwtAuthenticationEntryPoint.commence(request,response,e);
        }
    }


    private void login(String name) {
        User user = userService.getUserByUsername(name);
        user.setLastLogin(LocalDateTime.now());
        userService.updateById(user);
    }
}
